package base.util.lib;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("all")
public class VoHelper {

	/** 
	 * @param obj
	 *            实体 对象
	 * @param sql
	 * @param list
	 *            二维数组(Object[][])
	 * @return
	 * @throws Exception
	 */
	public static List toVoList(Object obj, String sql, List list) throws Exception {
		List resultlist = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			Object[] arr = (Object[]) list.get(i);
			obj = setObjectModel(obj, sql, arr);
			resultlist.add(obj);
		}
		return resultlist;
	}

	/** 
	 * @param obj
	 *            实体 对象
	 * @param sql
	 * @param list
	 *            二维数组(Object[][])
	 * @return
	 * @throws Exception
	 */
	//在查询中有as关键字
	public static List toVoListForSql(Object obj, String sql, List list) throws Exception {
		List resultlist = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			Object[] arr = (Object[]) list.get(i);
			obj = setObjectModelForSql(obj, sql, arr);
			resultlist.add(obj);
		}
		return resultlist;
	}

	/**
	 * @param obj
	 *            实体对象
	 * @param sql
	 * @param arr
	 *            Object []
	 * @return
	 * @throws Exception
	 */
	public static Object setObjectModel(Object obj, String sql, Object[] arr)
			throws Exception {
		sql = sql.toLowerCase();
		String str = sql.substring(sql.indexOf("select") + 6, sql.indexOf("from"));
		String strarr[] = str.split(",");
		int index = -1;
		// 获得对象的类型
		Class classType = obj.getClass();
		// System.out.println("********************begin******************************");
		// 通过默认构造方法去创建一个新的对象，getConstructor的视其参数决定调用哪个构造方法
		Object objectCopy = classType.getConstructor(new Class[] {}).newInstance(new Object[] {});
		// 获得对象的所有属性
		Field[] fields = classType.getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			// 获取数组中对应的属性
			Field field = fields[i];
			String fieldName = field.getName();
			String stringLetter = fieldName.substring(0, 1).toUpperCase();
			String setName = "set" + stringLetter + fieldName.substring(1);
			Method setMethod = classType.getMethod(setName, new Class[] { field
					.getType() });
			// System.out.println("fieldName: "+fieldName);
			// 调用源对象的 getXXX（）方法
			String value = null;
			try {
				index=getIndex(strarr,fieldName);
				if(index!=-1){
				value = arr[index].toString();
				
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			// 根据 字段类型 设置值
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String typeName = field.getType().getName();
			if (null != value && "" != value) {		
				try {
					if (typeName.equals("java.lang.String")) {
						setMethod.invoke(objectCopy, value);
						
					} else if (typeName.equals("java.lang.Long")) {
						setMethod.invoke(objectCopy, Long.parseLong(value));
						
					} else if (typeName.equals("long")) {
						setMethod.invoke(objectCopy, Long.parseLong(value));
						
					}else if (typeName.equals("java.util.Date")) {
						setMethod.invoke(objectCopy, format.parse(value));

					} else if (typeName.equals("java.math.BigDecimal")) {
						setMethod.invoke(objectCopy, BigDecimal.valueOf(Long
								.parseLong(value)));
						
					} else if (typeName.equals("java.lang.Double")) {
						setMethod.invoke(objectCopy, java.lang.Double
								.parseDouble(value));
						
					}else if (typeName.equals("double")) {
							setMethod.invoke(objectCopy, java.lang.Double
									.parseDouble(value));
							
					}else if (typeName.equals("java.lang.Integer")) {
						setMethod.invoke(objectCopy, java.lang.Integer
								.parseInt(value));
					}else if (typeName.equals("int")) {
						setMethod.invoke(objectCopy, java.lang.Integer
								.parseInt(value));
					}
					
					
				} catch (Exception e) {

				}
			}
		}
		return objectCopy;
	}

	/**
	 * @param obj
	 *            实体对象
	 * @param sql
	 * @param arr
	 *            Object []
	 * @return
	 * @throws Exception
	 */
	public static Object setObjectModelForSql(Object obj, String sql,
			Object[] arr) throws Exception {
		sql = sql.toLowerCase();
		String str = sql.substring(sql.indexOf("select") + 6, sql.indexOf("from"));
		String strarr[] = str.split(",");
		int index = -1;
		// 获得对象的类型
		Class classType = obj.getClass();
		// System.out.println("********************begin******************************");
		// 通过默认构造方法去创建一个新的对象，getConstructor的视其参数决定调用哪个构造方法
		Object objectCopy = classType.getConstructor(new Class[] {}).newInstance(new Object[] {});
		// 获得对象的所有属性
		Field[] fields = classType.getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			// 获取数组中对应的属性
			Field field = fields[i];
			String fieldName = field.getName();
			String stringLetter = fieldName.substring(0, 1).toUpperCase();
			String setName = "set" + stringLetter + fieldName.substring(1);
			Method setMethod = classType.getMethod(setName, new Class[] { field
					.getType() });
			// System.out.println("fieldName: "+fieldName);
			// 调用源对象的 getXXX（）方法
			String value = null;
			try {
				index = getIndexForSql(strarr, fieldName);
				if (index != -1) {
					value = arr[index].toString();
				}
			} catch (Exception e) {
				continue;
			}
			// 根据 字段类型 设置值
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String typeName = field.getType().getName();
			if (null != value && "" != value) {
				try {
					if (typeName.equals("java.lang.String")) {
						setMethod.invoke(objectCopy, value);

					} else if (typeName.equals("java.lang.Long")) {
						setMethod.invoke(objectCopy, Long.parseLong(value));

					} else if (typeName.equals("java.util.Date")) {
						setMethod.invoke(objectCopy, format.parse(value));

					} else if (typeName.equals("java.math.BigDecimal")) {
						setMethod.invoke(objectCopy, BigDecimal.valueOf(Long
								.parseLong(value)));
					} else if (typeName.equals("java.lang.Double")) {
						setMethod.invoke(objectCopy, java.lang.Double
								.parseDouble(value));

					} else if (typeName.equals("java.lang.Integer")) {
						setMethod.invoke(objectCopy, java.lang.Integer
								.parseInt(value));
					}
				} catch (Exception e) {

				}
			}
		}
		return objectCopy;
	}

	public static int getIndex(String[] array, String filename) {
		if (filename == null && "" == filename) {
			return -1;
		}
		if (array == null) {
			return -1;
		}
		for (int i = 0; i < array.length; i++) {
			if (array[i] == null && "" == array[i]) {
				continue;
			}
			if (filename.trim().equals(array[i].trim())) {
				return i;
			}
		}
		return -1;
	}

	public static int getIndexForSql(String[] array, String filename) {
		if (filename == null && "" == filename) {
			return -1;
		}
		if (array == null) {
			return -1;
		}
		for (int i = 0; i < array.length; i++) {
			if (array[i] == null && "" == array[i]) {
				continue;
			}
			array[i] = array[i].trim().toLowerCase();
			String temp_str = array[i].substring(array[i].indexOf(" as ") + 4, array[i].length());
			if (filename.trim().equals(temp_str)) {
				return i;
			}
		}
		return -1;
	}
	/**
	 * @param sql
	 * @param list
	 *            二维数组(Object[][])
	 * @return
	 * @throws Exception
	 */
	//在查询中有as关键字
	public static List toVoListForMap(String sql, List list) throws Exception {
		List resultlist = new ArrayList();
		 sql=sql.toLowerCase();
	     String str=sql.substring(sql.indexOf("select")+6, sql.indexOf("from"));
	     System.out.print(str);
	     String strarr[]=str.split(",");
			for (int i = 0; i < list.size(); i++) {
			 Object[] arr = (Object[]) list.get(i);
			 Map map=new HashMap();
			for(int j=0;j<strarr.length;j++){
				String key="";
				key= strarr[j].trim().substring(strarr[j].trim().indexOf(" as ") + 4, strarr[j].trim().length());
				String value="";
				if(arr[j] !=null){
					value= arr[j].toString();	
				}
				if(key !=null){
					key=key.trim();
				}
				map.put(key, value);
				
				value="";
				key="";
			}
			resultlist.add(map);
		}
		return resultlist;
	}
	
	
	
}
